#pragma once
#include <string>
#include <cstdio>
#include <cstring>
#include <unordered_set>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
//static const int gnum = 1024;
using namespace std;
struct user{
public:
    std::string _id;
    uint16_t _port;
    user(std::string id,uint16_t port) :_id(id),_port(port)
    {}
};

class Manager{
public:
    void add(std::string ip,uint16_t port){
        string s = ip + to_string(port);
        if(users.count(s) == 0){
            users.insert(make_pair(s,user(ip,port)));
        }
    }

    void del(std::string ip,uint16_t port){
        string s = ip + to_string(port);
        users.erase(s);
    }

    bool is_in(std::string ip,uint16_t port){
        string s = ip + to_string(port);
        return users.count(s);
    }

    void broadcastmessage(std::string ip,uint16_t port,std::string message,int sockfd){
        for(const auto& user:users){
            sockaddr_in client;
            socklen_t len = sizeof client;
            client.sin_family = AF_INET;
            client.sin_addr.s_addr = inet_addr(user.second._id.c_str());
            client.sin_port = htons(user.second._port);
            char buffer[1024];
            sprintf(buffer,"%s-[%hu] : %s",ip.c_str(),port,message.c_str());
            sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr*)&client,len);
        }
    }
private:
    std::unordered_map<string,user> users;
};